<?php
/**
 * Created by PhpStorm.
 * User: 刘翰文
 * Date: 2018/8/30
 * Time: 8:10
 */

namespace app\api\service;

use app\api\model\OrderMaster as OrderMasterModel;
use app\api\model\OrderDetail as OrderDetailModel;
use app\api\model\Useris as UserModel;
use think\Config;
use WxPay\WxPayApi;
use WxPay\WxPayJsApiPay;
use WxPay\WxPayUnifiedOrder;

require '../extend/WxPay/WxPay.Api.php';

class PayService extends BaseService
{
    /*1、检查订单(同时加入总价)
     *2、获取openid
     *3、订单预支付
     *4、计算签名
     *5、返回数据
     */

    /**
     * 需要商户订单号以及总价（分）及OPENID
     */
    private $order_id;
    private $order;
    private $orderDetail;
    private $open_id;
    private $price;//分

    //统一下单，WxPayUnifiedOrder中out_trade_no、body、total_fee、trade_type必填

    public function pay($order_id){
        $this->order_id = $order_id;
        self::GetOpenId();
        self::GetPrice();

        $result=self::PrePayOrder();
        $wxresult=self::getPayResult($result);
        OrderMasterModel::update([
            'prepay_id' => $wxresult['prepay_id']
        ],['id' => $this->open_id]);
        return  self::sign($wxresult);
    }

    public function GetOpenId(){
        $this->order = OrderMasterModel::where(['id' => $this->order_id])->find();
        $user = UserModel::where(['id' => $this->order['useris_id']])->find();
        $a = $user['openid'];
        $this->open_id = $a;
    }

    public function GetPrice(){
        $this->orderDetail = OrderDetailModel::where(['order_id' => $this->order_id])->select();

        foreach ($this->orderDetail as $detail){
            $price = $detail['price'];
            $num = $detail['num'];
            $this->price += $price * $num;
        }

        $this->price *= 100;
    }

    public function PrePayOrder(){
        $paydata= new WxPayUnifiedOrder();

//        $bodys = OrderDetail::where(['order_id' => $this->order_id])->with('product')->select();
//
//        $body = "";
//
//        for($i = 0 ;$i<sizeof($bodys);$i++){
//            $body = $body.$bodys[$i]['product']['product_name'];
//        }

        $out_trade_no = 100000 + $this->order_id;
        $paydata->SetOut_trade_no($out_trade_no);
        $paydata->SetTrade_type('JSAPI');
        $paydata->SetTotal_fee($this->price);
        $paydata->SetBody("医管家订单支付");//设置body
        $paydata->SetOpenid($this->open_id);
        $paydata->SetNotify_url(config('wx.notify'));

        return $paydata;
    }

    public function getPayResult($paydata){
        $wxconfig= new WxPayConfig();
        $wxresult= WxPayApi::unifiedOrder($wxconfig,$paydata);

        /*if($wxresult['return_code'] != 'SUCCESS' || $wxresult['result_code'] !='SUCCESS'){
            throw new payExceptions(['msg'=>$wxresult]);
        }*/

        //Order::update(['prepay_id'=>$wxresult['prepay_id']],['id'=>$this->order_id]);

        return $wxresult;
    }

    public function sign($wxresult){
        $wxconfig=new WxPayConfig();
        $jsApiPayData = new WxPayJsApiPay();
        $jsApiPayData->SetAppid(config('wx.appid'));
        $jsApiPayData->SetTimeStamp((string)time());
        $rand = md5(time() . mt_rand(0, 1000));
        $jsApiPayData->SetNonceStr($rand);
        $jsApiPayData->SetPackage('prepay_id=' . $wxresult['prepay_id']);
        $jsApiPayData->SetSignType('MD5');
        $sign = $jsApiPayData->MakeSign($wxconfig);
        $rawValues = $jsApiPayData->GetValues();
        $rawValues['paySign'] = $sign;
        //unset($rawValues['appId']);
        //$wxresult['sign'] = $sign;
        return $rawValues;
    }
}